#coding:utf8
'''
共20000个数据的训练样本
并有10000个数据作为测试样本
信噪比为20dB
滑动窗口长度为12

'''

from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal
import time
import theano
import theano.tensor as T
from utils import generateData, calc_distance, psk8, psk16
import math
np.random.seed(123)

M,TT,dB,L = 3000, 2000, 20, 12
EqD = int(round((L+10)/2))
SNR = range(-10, 20)

title_size = 18
label_size = 16

###### RLS ######
def RLS(X,Tx, n=4):
    # 输入 测试用的X和Tx, 输出 权值和评分
    c = np.zeros( (1,L+1) );
    R_inverse = 100*np.eye(L+1)

    for k in range(TT-10):
        e = Tx[k+10+L-EqD] - c.dot( X[:,k+10]);
        filtered_infrmn_vect = R_inverse.dot(X[:,k+10]);  # (13,1)
        norm_error_power = np.conj(X[:,k+10].T).dot(filtered_infrmn_vect);
        gain_constant = 0.5 / (1 + norm_error_power);
        norm_filtered_infrmn_vect = gain_constant * np.conj(filtered_infrmn_vect.T);
        c = c + e * norm_filtered_infrmn_vect;
        R_inverse = R_inverse - np.conj(norm_filtered_infrmn_vect.reshape((13,1))).dot(norm_filtered_infrmn_vect.reshape((1,13)));

    sb = np.dot(c, X)
    pdvalue = sb.ravel()
    accuracy = score(pdvalue, Tx, n)
    return c,sb,accuracy
def score(pdvalue, Tx, n):
    count = 0
    for i in range(len(pdvalue)-20):
        rp = (pdvalue[i+10].real, pdvalue[i+10].imag)
        if n == 4 and pdvalue[i+10].imag * Tx[i+10+L-EqD].imag >= 0 and pdvalue[i+10].real * Tx[i+10+L-EqD].real >=0:
            count += 1
        if n == 8 and calc_distance(rp, (Tx[i+10+L-EqD].real, Tx[i+10+L-EqD].imag)) == min(map(lambda p: calc_distance(rp, p), psk8)):
            count += 1
        if n == 16 and calc_distance(rp, (Tx[i+10+L-EqD].real, Tx[i+10+L-EqD].imag)) == min(map(lambda p: calc_distance(rp, p), psk16)):
            count += 1
    return count / (len(pdvalue)-20)

# res = []
# for i in range(-10, 30):
#     X, Tx, x = generate8Data(3000, 2000, i, 12)
#     rls_weights, sb, accuracy = RLS(X,Tx,n=8)
#     res.append(accuracy)
# print res

# res = []
# for i in range(-10, 30):
#     X, Tx, x = generate16Data(3000, 2000, i, 12)
#     rls_weights, sb, accuracy = RLS(X,Tx,n=16)
#     res.append(accuracy)
# print res
plt.rcParams['font.sans-serif']=['simhei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号
fig = plt.figure()
plt.subplots_adjust(hspace=0.4,wspace=0.4)



ax1 = fig.add_subplot(2,3,1)
ax1.scatter([1,1,-1,-1],[1,-1,-1,1])
ax1.set_title(u"QPSK星座图", fontsize=title_size)
ax1.set_xlabel(u"实部", fontsize=label_size)
ax1.set_ylabel(u"虚部", fontsize=label_size)

ax2 = fig.add_subplot(2,3,2)
ax2.scatter(map(lambda x: x[0], psk8), map(lambda x: x[1], psk8))
ax2.set_title(u"8PSK星座图", fontsize=title_size)
ax2.set_xlabel(u"实部", fontsize=label_size)
ax2.set_ylabel(u"虚部", fontsize=label_size)

ax3 = fig.add_subplot(2,3,3)
ax3.scatter(map(lambda x: x[0], psk16), map(lambda x: x[1], psk16))
ax3.set_title(u"16PSK星座图", fontsize=title_size)
ax3.set_xlabel(u"实部", fontsize=label_size)
ax3.set_ylabel(u"虚部", fontsize=label_size)


ax4 = fig.add_subplot(2,3,4)
X, Tx, x = generateData(3000, 2000, 30, 12)
rls_weights, sb, accuracy = RLS(X, Tx, n=4)
ax4.scatter(sb[0].real, sb[0].imag)
ax4.set_title(u"QPSK均衡结果", fontsize=title_size)
ax4.set_xlabel(u"实部", fontsize=label_size)
ax4.set_ylabel(u"虚部", fontsize=label_size)

ax5 = fig.add_subplot(2,3,5)
X, Tx, x = generateData(3000, 2000, 30, 12, qn=8)
rls_weights, sb, accuracy = RLS(X, Tx, n=8)
ax5.scatter(sb[0].real, sb[0].imag)
ax5.set_title(u"8PSK均衡结果", fontsize=title_size)
ax5.set_xlabel(u"实部", fontsize=label_size)
ax5.set_ylabel(u"虚部", fontsize=label_size)

ax6 = fig.add_subplot(2,3,6)
X, Tx, x = generateData(3000, 2000, 30, 12, qn=16)
rls_weights, sb, accuracy = RLS(X, Tx, n=16)
ax6.scatter(sb[0].real, sb[0].imag)
ax6.set_title(u"16PSK均衡结果", fontsize=title_size)
ax6.set_xlabel(u"实部", fontsize=label_size)
ax6.set_ylabel(u"虚部", fontsize=label_size)

plt.show()


# X, Tx, x = generateData(3000,2000,20,12)
# X_2, Tx_2, x_2 = generateData(3000,2000,10,12)
# from datetime import datetime
# start = datetime.now()
# rls_weights, sb, accuracy = RLS(X,Tx)
# delta = datetime.now() - start
# print(delta.seconds, delta.microseconds)
# _, sb_lms, ac = RLS(X_2,Tx_2)
# print('RLS accuracy: {}'.format(accuracy))



# res = []
# for i in range(-10, 20):
#     X, Tx, x = generateData(3000,2000,i,12)
#     from datetime import datetime
#     start = datetime.now()
#     rls_weights, sb, accuracy = RLS(X,Tx)
#     delta = datetime.now() - start
#     res.append(delta)
# print(res)

# print Tx.shape, sb.shape
# # print plt.rcParams.keys()
# plt.rcParams['font.sans-serif']=['simhei'] #用来正常显示中文标签

# plt.rcParams['axes.unicode_minus']=False #用来正常显示负号
# fig = plt.figure()
# plt.subplots_adjust(hspace=0.4,wspace=0.3)

# ax1 = fig.add_subplot(2,2,1)
# ax1.scatter(Tx.real, Tx.imag)
# ax1.set_title(u"发送符号", fontsize=title_size)
# ax1.set_xlabel(u"实部", fontsize=label_size)
# ax1.set_ylabel(u"虚部", fontsize=label_size)

# ax2 = fig.add_subplot(2,2,2)
# ax2.scatter(x.real, x.imag)
# ax2.set_title(u"接收端符号", fontsize=title_size)
# ax2.set_xlabel(u"实部", fontsize=label_size)
# ax2.set_ylabel(u"虚部", fontsize=label_size)


# ax3 = fig.add_subplot(2,2,3)
# ax3.scatter(sb_lms[0].real, sb_lms[0].imag)
# ax3.set_title(u"LMS", fontsize=title_size)
# ax3.set_xlabel(u"实部", fontsize=label_size)
# ax3.set_ylabel(u"虚部", fontsize=label_size)

# ax4 = fig.add_subplot(2,2,4)
# ax4.scatter(sb[0].real, sb[0].imag)
# ax4.set_title("RLS", fontsize=title_size)
# ax4.set_xlabel(u"实部", fontsize=label_size)
# ax4.set_ylabel(u"虚部", fontsize=label_size)
# # plt.savefig('foo.png')
# # plt.show()
# plt.show()

# fig = plt.figure()
